package com.fenrirtec.aepp.common.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fenrirtec.aepp.common.dao.SystemConfigDao;
import com.fenrirtec.aepp.common.model.SystemConfig;
import com.fenrirtec.core.database.DatabaseSessionManager;
import com.fenrirtec.core.database.ResultSetMapper;
import com.fenrirtec.core.exception.DatabaseException;

public class SystemConfigDao_JDBCImpl implements SystemConfigDao {

	private static final Logger logger = LoggerFactory.getLogger(SystemConfigDao_JDBCImpl.class);

	@Override
	public SystemConfig load() {
		if (logger.isInfoEnabled()) {
			logger.info("[SystemConfigDao_JDBCImpl#load] start.");
		}

		PreparedStatement statement = null;
		
		try {
			StringBuilder sql = new StringBuilder()
				.append("select \n")
				.append("  password, \n")
				.append("  change_password, \n")
				.append("  regist_enabled, \n")
				.append("  news_count, \n")
				.append("  tender_count, \n")
				.append("  tender_sort, \n")
				.append("  member_count, \n")
				.append("  contact_copy_required, \n")
				.append("  license_copy_required, \n")
				.append("  legal_copy_required, \n")
				.append("  physical_delete, \n")
				.append("  upload_root_folder, \n")
				.append("  qualifications_save_folder, \n")
				.append("  images_save_folder, \n")
				.append("  upload_temp_folder, \n")
				.append("  allowed_image_extension, \n")
				.append("  allowed_image_size, \n")
				.append("  allowed_doc_extension, \n")
				.append("  allowed_doc_size, \n")
				.append("  allowed_compress_extension, \n")
				.append("  allowed_compress_size, \n")
				.append("  create_user, \n")
				.append("  create_date, \n")
				.append("  update_user, \n")
				.append("  update_date, \n")
				.append("  delete_flag \n")
				.append("from \n")
				.append("  t_system_config \n")
				.append("where \n")
				.append("  delete_flag = false \n");
			
			if (logger.isTraceEnabled()) {
				logger.trace("[SystemConfigDao_JDBCImpl#load] sql={}", sql);
			}
			
			Connection connection = DatabaseSessionManager.getInstance().getSession();
			statement = connection.prepareStatement(sql.toString());
			ResultSet resultSet = statement.executeQuery();
			
			ResultSetMapper<SystemConfig> resultSetMapper = new ResultSetMapper<SystemConfig>();
			SystemConfig systemConfig = resultSetMapper.mapResultSetToObject(resultSet, SystemConfig.class);
			
			return systemConfig;
			
		} catch (SQLException e) {
			if (logger.isTraceEnabled()) {
				logger.trace("[SystemConfigDao_JDBCImpl#load] sql error occurred.", e);
			}
			throw new DatabaseException("database error occurred.", e);
		} finally {
			if (logger.isInfoEnabled()) {
				logger.info("[SystemConfigDao_JDBCImpl#load] finish.");
			}
			if (statement != null) { try { statement.close(); } catch (SQLException e) {} }
		}
	}

	@Override
	public Boolean changePassword(String loginName, String password) {
		
		if (logger.isInfoEnabled()) {
			logger.info("[SystemConfigDao_JDBCImpl#changePassword] start.");
		}

		PreparedStatement statement = null;
		
		try {
			StringBuilder sql = new StringBuilder();
			if ("admin".equalsIgnoreCase(loginName)) {
				sql.append("update t_system_config \n");
				sql.append("set \n");
				sql.append("  password = ?, \n");
				sql.append("  change_password = ?, \n");
				sql.append("  update_user = ?, \n");
				sql.append("  update_date = now() \n");
			} else {
				sql.append("update t_user \n");
				sql.append("set \n");
				sql.append("  login_password = ?, \n");
				sql.append("  update_user = ?, \n");
				sql.append("  update_date = now() \n");
				sql.append("where \n");
				sql.append("  login_name = ? \n");
				sql.append("and \n");
				sql.append("  delete_flag = ? \n");
			}
			
			if (logger.isTraceEnabled()) {
				logger.trace("[SystemConfigDao_JDBCImpl#changePassword] sql={}", sql);
			}
			
			Connection connection = DatabaseSessionManager.getInstance().getSession();
			statement = connection.prepareStatement(sql.toString());
			
			int paramIdx = 0;
			if ("admin".equalsIgnoreCase(loginName)) {
				statement.setString(++paramIdx, password);
				statement.setBoolean(++paramIdx, false);
				statement.setString(++paramIdx, loginName);
			} else {
				statement.setString(++paramIdx, password);
				statement.setString(++paramIdx, loginName);
				statement.setString(++paramIdx, loginName);
				statement.setBoolean(++paramIdx, false);
			}
			
			return statement.executeUpdate() == 1;
			
		} catch (SQLException e) {
			if (logger.isTraceEnabled()) {
				logger.trace("[SystemConfigDao_JDBCImpl#changePassword] sql error occurred.", e);
			}
			throw new DatabaseException("database error occurred.", e);
		} finally {
			if (logger.isInfoEnabled()) {
				logger.info("[SystemConfigDao_JDBCImpl#changePassword] finish.");
			}
			if (statement != null) { try { statement.close(); } catch (SQLException e) {} }
		}
	}

	@Override
	public Boolean updateSystemConfig(SystemConfig systemConfig) {
		if (logger.isInfoEnabled()) {
			logger.info("[SystemConfigDao_JDBCImpl#updateSystemConfig] start.");
		}

		PreparedStatement statement = null;
		
		try {
			StringBuilder sql = new StringBuilder();
			sql.append("update t_system_config \n");
			sql.append("set \n");
			if (StringUtils.isNotEmpty(systemConfig.getPassword())) {
				sql.append("  password = ?, \n");
			}
			sql.append("  regist_enabled = ?, \n");
			sql.append("  news_count = ?, \n");
			sql.append("  tender_count = ?, \n");
			sql.append("  tender_sort = ?, \n");
			sql.append("  member_count = ?, \n");
			sql.append("  contact_copy_required = ?, \n");
			sql.append("  license_copy_required = ?, \n");
			sql.append("  legal_copy_required = ?, \n");
			sql.append("  physical_delete = ?, \n");
			sql.append("  upload_root_folder = ?, \n");
			sql.append("  qualifications_save_folder = ?, \n");
			sql.append("  images_save_folder = ?, \n");
			sql.append("  upload_temp_folder = ?, \n");
			sql.append("  allowed_image_extension = ?, \n");
			sql.append("  allowed_image_size = ?, \n");
			sql.append("  allowed_doc_extension = ?, \n");
			sql.append("  allowed_doc_size = ?, \n");
			sql.append("  allowed_compress_extension = ?, \n");
			sql.append("  allowed_compress_size = ?, \n");
			sql.append("  update_user = ?, \n");
			sql.append("  update_date = current_timestamp \n");
			sql.append("where \n");
			sql.append("  delete_flag = false \n");
			
			if (logger.isTraceEnabled()) {
				logger.trace("[SystemConfigDao_JDBCImpl#updateSystemConfig] sql={}", sql);
			}
			
			Connection connection = DatabaseSessionManager.getInstance().getSession();
			statement = connection.prepareStatement(sql.toString());
			
			int paramIdx = 0;
			if (StringUtils.isNotEmpty(systemConfig.getPassword())) {
				statement.setString(++paramIdx, systemConfig.getPassword());
			}
			statement.setBoolean(++paramIdx, systemConfig.getRegistEnabled());
			statement.setInt(++paramIdx, systemConfig.getNewsCount());
			statement.setInt(++paramIdx, systemConfig.getTenderCount());
			statement.setInt(++paramIdx, systemConfig.getTenderSort());
			statement.setInt(++paramIdx, systemConfig.getMemberCount());
			statement.setBoolean(++paramIdx, systemConfig.getContactCopyRequired());
			statement.setBoolean(++paramIdx, systemConfig.getLicenseCopyRequired());
			statement.setBoolean(++paramIdx, systemConfig.getLegalCopyRequired());
			statement.setBoolean(++paramIdx, systemConfig.getPhysicalDelete());
			statement.setString(++paramIdx, systemConfig.getUploadRootFolder());
			statement.setString(++paramIdx, systemConfig.getQualificationsSaveFolder());
			statement.setString(++paramIdx, systemConfig.getImagesSaveFolder());
			statement.setString(++paramIdx, systemConfig.getUploadTempFolder());
			statement.setString(++paramIdx, systemConfig.getAllowedImageExtension());
			statement.setLong(++paramIdx, systemConfig.getAllowedImageSize());
			statement.setString(++paramIdx, systemConfig.getAllowedDocExtension());
			statement.setLong(++paramIdx, systemConfig.getAllowedDocSize());
			statement.setString(++paramIdx, systemConfig.getAllowedCompressExtension());
			statement.setLong(++paramIdx, systemConfig.getAllowedCompressSize());
			statement.setString(++paramIdx, systemConfig.getUpdateUser());
			
			return statement.executeUpdate() == 1;
			
		} catch (SQLException e) {
			if (logger.isTraceEnabled()) {
				logger.trace("[SystemConfigDao_JDBCImpl#updateSystemConfig] sql error occurred.", e);
			}
			throw new DatabaseException("database error occurred.", e);
		} finally {
			if (logger.isInfoEnabled()) {
				logger.info("[SystemConfigDao_JDBCImpl#updateSystemConfig] finish.");
			}
			if (statement != null) { try { statement.close(); } catch (SQLException e) {} }
		}
	}
}
